package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;

import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    //根据按照状态查询实名认证信息列表
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.检查参数
        dto.checkParam();//检查分页参数是否符合

        //2.准备分页参数,创建查询条件,分页条件,查询参数
        IPage<ApUserRealname> pagereq = new Page<>(dto.getPage(),dto.getSize());

        //创建条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //判断条件  //判断条件字段的有无
        //        //请求全部是,status等于null
        if (dto.getStatus()!=null){
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        IPage<ApUserRealname> pageResult = this.page(pagereq, queryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());
        return pageResponseResult;
    }

    @Autowired
    ApUserMapper apUserMapper;
    /**
     *
     * @param dto   拿实名认证的id,apuser的id和实名认证的user_id相关联
     * @param status
     * @return
     */
    @GlobalTransactional//设置全局事务(分布式事务,)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        if (dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证id不能为空");
        }

        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证数据不存在");
        }
        if (dto.getStatus()!= AdminConstants.WAIT_AUTH){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该实名认证不是待审核状态");
        }

        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的用户信息不存在");
        }

        apUserRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        //set完记得更新
        updateById(apUserRealname);

        if (status.equals(AdminConstants.AD_USER_ISSTATUS)){//判断两个包装类用equals来判断,包装类和int值做比较,用intvalue做转换
            //审核通过了,才需要验证身份证
//            boolean flag = IdCardUtils.checkIdCardInfo(apUserRealname.getName(), apUserRealname.getIdno());
//            if (flag){
//                CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"实名认证失败,身份证信息不匹配");
//            }

            WmUser wmUser=createWmUser(apUser);//创建自媒体
            if (wmUser==null||wmUser.getId()==null){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"创建自媒体用户账户信息失败");
            }
            //创建作者信息
          ResponseResult responseResult= createApAuthor(wmUser);
            if (responseResult.getCode()!=0){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR,responseResult.getErrorMessage());
            }
        }

        //int i=1/0;手动异常

        return ResponseResult.okResult();
    }



    /**
     * 远程创建自媒体账户
     * @param apUser
     * @return
     */
    @Autowired
    WemediaFeign wemediaFeign;
    private WmUser createWmUser(ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());//apuser和wemedia的用户名相同
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"自媒体账户已存在");
        }
        //为空的话,就需要新建
         wmUser = new WmUser();//前后是同一个参数
        BeanUtils.copyProperties(apUser,wmUser);//属性拷贝
        wmUser.setId(null);
        wmUser.setApUserId(apUser.getId());

        return wemediaFeign.save(wmUser);//保存成功后,返回的wmUser有id

    }

    @Autowired
    ArticleFeign articleFeign;
    private ResponseResult createApAuthor(WmUser wmUser) {
        //1.先查
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());

        if (apAuthor!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者账户已存在");
        }
        //2.创建
        apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());

        return articleFeign.save(apAuthor);

    }

}
